package com.huluobo.day_1_lifecycledemo.lifecycle;

import android.os.CountDownTimer;
import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.huluobo.day_1_lifecycledemo.viewmodel.ADViewModel;

/**
 * 倒计时广告管理器
 */
public class ADManager implements LifecycleObserver {

    private CountDownTimer countDownTimer;//倒计时工具

    public ADManager(ADViewModel adViewModel) {
        countDownTimer = new CountDownTimer(adViewModel.millisInFuture, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //每当倒计时时,set一下最新的倒计时给LiveData
                Log.i("TagA", "广告剩余:" + (int) millisUntilFinished / 1000);
                adViewModel.setAdTimingResult(millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                Log.i("TagA", "广告结束");
            }
        };
    }


    //lifecycle相关
    //开启倒计时的方法
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void start() {
        countDownTimer.start();
        Log.i("TagA", "开始计时");
    }

    //lifecycle相关
    //关闭倒计时的方法
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void stop() {
        countDownTimer.cancel();
        Log.i("TagA", "结束计时");
    }
}
